﻿(function () {
    RegisterSerializeObject();
}());

/*===注册类声明类型Start===*/
var Class = {
    create: function ()              // create Function  
    {
        return function () {
            this.initialize.apply(this, arguments);
        }
    }
};
/*===注册类声明类型End===*/

/*===表单提交实体Start===*/
var FormEntity = Class.create();
FormEntity.prototype =
    {
        //表单选择器
        selector: "",
        //表单提交地址
        url: "",
        //表单参数
        data: {},
        //表单数据实体
        formData: {},
        //表单提交方式
        type: "POST",
        //内容类型
        contentType: "application/x-www-form-urlencoded",
        //默认返回数据为json格式
        dataType: "json",
        //是否异步请求
        async: true,
        //是否缓存
        cache: false,
        //表单提交前事件
        submiting: function () {
            return true;
        },
        //表单提交失败事件
        submitFailed: function () {
        },
        //表单处理内容，默认Ajax表单提交
        handle: function () {
            var $this = this;
            //判断是否应用插件jquery.form.js，该插件支持Ajax文件上传
            if ($($this.selector).ajaxSubmit) {
                $($this.selector).ajaxSubmit({
                    cache: $this.cache,
                    type: $this.type,
                    url: $this.url,
                    data: $this.data,
                    dataType: $this.dataType,
                    contentType: $this.contentType,
                    async: $this.async,
                    success: function (InvokeResult) {
                        $this.submitSuccess(InvokeResult);
                        $this.submited();
                        if ($this.isClearData) {
                            $this.clearFormData();
                        }
                    }
                });
            } else {
                $.ajax({
                    cache: this.cache,
                    type: this.type,
                    url: this.url,
                    data: this.data,
                    dataType: this.dataType,
                    contentType: this.contentType,
                    async: this.async,
                    success: function (InvokeResult) {
                        $this.submitSuccess(InvokeResult);
                        $this.submited();
                        if ($this.isClearData) {
                            $this.clearFormData();
                        }
                    }
                });
            }
        },
        //表单提交
        submit: function () {
            if (!this.submiting()) {
                this.submitFailed();
                return;
            }
            this.handle();
        },
        //表单提交成功事件
        submitSuccess: function (invokeresult) {
        },
        //表单提交完成事件
        submited: function () {
        },
        //是否清楚表单数据
        isClearData: true,
        //清除表单数据
        clearFormData: function () {
            $(this.selector).find(':input').each(
                function () {
                    switch (this.type) {
                        case 'passsword':
                        case 'select-multiple':
                        case 'select-one':
                        case 'text':
                        case 'textarea':
                            $(this).val('');
                            break;
                        case 'checkbox':
                        case 'radio':
                            this.checked = false;
                    }
                }
            );
        },
        //构造函数
        initialize: function (selector) {
            this.selector = selector;
            this.data = $(this.selector).serialize();
            this.formData = $(this.selector).serializeObject()
        }
    };
/*===表单提交实体End===*/

/*===Ajax请求实体Start===*/
var AjaxEntity = Class.create();
AjaxEntity.prototype =
    {
        //请求地址
        url: "",
        //请求参数
        data: {},
        //请求方式
        type: "POST",
        //默认返回数据为json格式
        dataType: "json",
        //内容类型
        contentType: "application/x-www-form-urlencoded",
        //是否异步请求
        async: true,
        //是否缓存
        cache: false,
        //请求前事件
        executing: function () {
            return true;
        },
        //请求失败事件
        executeFailed: function () {
        },
        //请求事件
        execute: function () {
            if (!this.executing()) {
                this.executeFailed();
                return;
            }
            var $this = this;
            $.ajax({
                cache: this.cache,
                type: this.type,
                url: this.url,
                data: this.data,
                dataType: this.dataType,
                contentType: this.contentType,
                async: this.async,
                success: function (InvokeResult) {
                    $this.executeSuccess(InvokeResult);
                    $this.executed();
                }
            });
        },
        //请求成功事件
        executeSuccess: function (invokeresult) {
        },
        //请求完成事件
        executed: function () {
        },
        //构造函数
        initialize: function () {
        }
    };
/*===Ajax请求实体End===*/

/*===定时任务实体Start===*/
var TimePlan = Class.create();
TimePlan.prototype = {
    //构造函数
    initialize: function (targetTime) {
        this.targetTime = targetTime;
        this.targetMilliSecond = (function (_targetTime) {
            var f = _targetTime.split(' ', 2);
            var d = (f[0] ? f[0] : '').split('-', 3);
            var t = (f[1] ? f[1] : '').split(':', 3);
            return (new Date(
            parseInt(d[0], 10) || null,
            (parseInt(d[1], 10) || 1) - 1,
            parseInt(d[2], 10) || null,
            parseInt(t[0], 10) || null,
            parseInt(t[1], 10) || null,
            parseInt(t[2], 10) || null
            )).getTime();
        }(this.targetTime));
        this.remainTime = { Day: 0, Hour: 0, Minute: 0, Second: 0 };
        window.TimePlanTemp = this;
    },
    //目标时间
    targetTime: "",
    //剩余时间
    remainTime: {},
    //要执行的任务
    work: function () { },
    //任务结束后事件
    completed: function () { },
    //间隔时间（默认1s）
    perTime: 1,
    //任务ID
    planID: null,
    //执行任务
    executePlan: function () {
        var self = window.TimePlanTemp;
        var startTime = self.targetMilliSecond;
        var currentTime = new Date();
        var result = (startTime - Date.parse(currentTime)) / 1000;
        if (result >= 0) {
            self.remainTime.Day = parseInt(result / 24 / 3600);
            self.remainTime.Hour = parseInt((result / 3600) % 24);
            self.remainTime.Minute = parseInt((result / 60) % 60);
            self.remainTime.Second = parseInt(result % 60);
            $plan = self.executePlan;
            if (!self.planID) {
                self.planID = setInterval(function () { $plan(); }, self.perTime * 1000);
            }
            self.work();
        }
        else {
            if (self.planID) {
                clearInterval(self.planID);
                self.completed();
            }
            delete window.TimePlanTemp;
        }
    }
};
/*===定时任务实体End===*/

/*===文件上传Start===*/
var FileUpload = Class.create();
FileUpload.prototype = {
    //宽度
    width: 80,
    //是否自动上传，默认true
    auto: true,
    //Flash路径
    swf: '/Content/uploadify/uploadify.swf',
    //上传地址
    url: "",
    //上传按钮名称
    buttonText: "选择文件",
    //上传按钮图片
    buttonImage: null,
    //上传按钮样式
    buttonClass: '',
    //是否多文件上传，默认单文件
    multi: false,
    //附带表单数据，如{ "objUploadSet": $('#file_upload').attr("data-options") }
    formData: {},
    //提交到服务端的Name名称
    fileObjName: "FileData",
    //上传文件后缀
    fileTypeExts: '*.*',
    //上传文件大小，默认不限制
    fileSizeLimit: 0,
    //上传文件数量
    uploadLimit: 0,
    //上传进度自定义模板
    itemTemplate: "",
    //上传成功事件
    uploadSuccess: function (objFile, objInvokeResult) { },
    //上传完成事件
    uploaded: function () {
        return true;
    },
    //初始化配置
    uploadify: function (setts) {
        setts = setts || {};
        $this = this;
        var defaultSetts = {
            width: 80,
            auto: $this.auto,
            swf: $this.swf,
            uploader: $this.url,
            buttonText: $this.buttonText,
            buttonImage: $this.buttonImage,
            buttonClass: $this.buttonClass,
            multi: $this.multi,
            formData: $this.formData,
            fileObjName: $this.fileObjName,
            fileTypeExts: $this.fileTypeExts,
            fileSizeLimit: $this.fileSizeLimit,
            uploadLimit: $this.uploadLimit,
            //itemTemplate: '<div class="uploadifive-queue-item"><span class="filename"></span> | <span class="fileinfo"></span><div class="close"></div></div>',
            itemTemplate: $this.itemTemplate,
            onUploadSuccess: function (objFile, objInvokeResult) {
                if (JSON.parse) {
                    objInvokeResult = JSON.parse(objInvokeResult);
                } else {
                    objInvokeResult = eval("(" + objInvokeResult + ")");
                }
                $this.uploadSuccess(objFile, objInvokeResult);
                $this.uploaded();
            }
        };
        $.extend(true, defaultSetts, setts);
        $(this.selector).uploadify(defaultSetts);
    },
    //构造函数
    initialize: function (selector) {
        this.selector = selector;
    }
};
/*===文件上传End===*/

//扩展JQuery实例对象serializeObject方法
function RegisterSerializeObject() {
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
}

//Json日期串后转成日期格式
function JsonToDate(objJsonDate) {
    var objDate = new Date(Number(objJsonDate.replace("/Date(", "").replace(")/", "")));
    return FormatDate(objDate, true);
}

//日期格式化
function FormatDate(objDate, isShowDetail) {
    var objYear = objDate.getFullYear();
    var objMonth = objDate.getMonth();
    objMonth = objMonth + 1 < 10 ? "0" + (objMonth + 1) : objMonth + 1;
    var objDay = objDate.getDate();
    objDay = objDay < 10 ? "0" + objDay : objDay;
    isShowDetail = isShowDetail || true;
    if (isShowDetail) {
        var objHour = objDate.getHours();
        objHour = objHour < 10 ? "0" + objHour : objHour;
        var objMinute = objDate.getMinutes();
        objMinute = objMinute < 10 ? "0" + objMinute : objMinute;
        var objSecond = objDate.getSeconds();
        objSecond = objSecond < 10 ? "0" + objSecond : objSecond;
        return objYear + "-" + objMonth + "-" + objDay + " " + objHour + ":" + objMinute + ":" + objSecond;
    }
    return objYear + "-" + objMonth + "-" + objDay;
}

function ParserDate(objDateString) {
    if (!objDateString) return new Date();
    var objDate = (objDateString.split(' '));
    var ymd = (objDate[0].split('-'));
    var objYear = parseInt(ymd[0], 10);
    var objMonth = parseInt(ymd[1], 10);
    var objDay = parseInt(ymd[2], 10);
    var hms = (objDate[1].split(':'));
    var objHour = parseInt(hms[0], 10);
    var objMinute = parseInt(hms[1], 10);
    var objSecond = parseInt(hms[2], 10);
    if (!isNaN(objYear) && !isNaN(objMonth) && !isNaN(objDay) && !isNaN(objHour) && !isNaN(objMinute) && !isNaN(objSecond)) {
        return new Date(objYear, objMonth - 1, objDay, objHour, objMinute, objSecond);
    } else {
        return new Date();
    }
}


//布尔类型格式化
function BooleanToString(val) {
    if (val && Boolean(val)) {
        return "是";
    } else {
        return "否";
    }
}

//字符串转Json
function StringToJosn(val) {
    try{
        return JSON.parse(val);
    } catch (e) {
        return eval("(" + val + ")");
    }
}